/**
 * 文件名：@DefaultHandlerExceptionResolver.java <br/>
 * 包名：cn.efunbox.afw.web.mvc.exception <br/>
 * 项目名：afw-web <br/>
 * @author xtwin <br/>
 */
package cn.efunbox.afw.web.mvc.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import cn.efunbox.afw.web.entity.HttpResult;
import cn.efunbox.afw.web.mvc.view.ViewNameResolver;
import cn.efunbox.afw.web.util.AfwWebConstant;

/**
 * 类名：DefaultHandlerExceptionResolver  <br />
 *
 * 功能：异常处理器
 *
 * @author xtwin <br />
 * 创建时间：2016年8月5日 上午1:20:20  <br />
 * @version 2016年8月5日
 */
public class DefaultHandlerExceptionResolver implements HandlerExceptionResolver {
	
	// 日志记录器
	private static final Logger logger = LoggerFactory.getLogger(DefaultHandlerExceptionResolver.class);
	
	// 视图名称解析器
	protected ViewNameResolver viewNameResolver;
	
	// 异常模型解析器
	protected ExceptionModelResolver exceptionModelResolver;
	
	/**
	 * 功能: <br/>
	 * 
	 * 重写：xtwin <br/>
	 * 
	 * @version ：2016年8月5日 上午1:22:22<br/>
	 * 
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 * @return <br/>
	 * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
		
		// 记录日志
		logger.error("The exception is : " + String.valueOf(e), e);
		try {
			ModelAndView mav = new ModelAndView();
			
			// 视图名称
			mav.setViewName(viewNameResolver.resolve(request));

			// 解析异常数据
			HttpResult<?> ret = exceptionModelResolver.resolve(request, response, e);
			
			// 状态码
			response.setStatus(ret.getStatus());
			
			// 添加数据
			mav.addObject(AfwWebConstant.KEY_RETURN_VALUE, ret.getBody());
			
			// 返回
			return mav;
		} catch (Exception ex) {
			logger.error("The resolve exception is : " + String.valueOf(ex), ex);
		}
		
		return null;
	}

	/**
	 * @version 2016年8月5日-上午1:24:56
	 */
	public void setViewNameResolver(ViewNameResolver viewNameResolver) {
		this.viewNameResolver = viewNameResolver;
	}

	/**
	 * @version 2016年8月5日-上午3:17:33
	 */
	public void setExceptionModelResolver(ExceptionModelResolver exceptionModelResolver) {
		this.exceptionModelResolver = exceptionModelResolver;
	}
}